/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm),'');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}
/**
 * 时间戳转换工具类
 */

/**
 * 将时间戳转换为年月日时分秒格式
 * @param {number} timestamp - 时间戳（秒或毫秒）
 * @param {string} format - 格式类型，可选：'full' | 'date' | 'time' | 'custom'
 * @param {string} separator - 日期分隔符，默认 '-'
 * @returns {string} 格式化后的时间字符串
 */
export function formatTimestamp(timestamp, format = 'full', separator = '-') {
  if (!timestamp) return ''
  
  // 自动检测时间戳是秒还是毫秒（10位是秒，13位是毫秒）
  const ts = timestamp.toString().length === 10 ? timestamp * 1000 : timestamp
  
  const date = new Date(ts)
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    return '无效日期'
  }
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  switch (format) {
    case 'date':
      return `${year}${separator}${month}${separator}${day}`
    case 'time':
      return `${hours}:${minutes}:${seconds}`
    case 'full':
      return `${year}${separator}${month}${separator}${day} ${hours}:${minutes}:${seconds}`
    case 'custom':
      // 自定义格式，可以根据需要扩展
      return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
    default:
      return `${year}${separator}${month}${separator}${day} ${hours}:${minutes}:${seconds}`
  }
}

/**
 * 将时间戳转换为相对时间（如：刚刚、5分钟前、3天前）
 * @param {number} timestamp - 时间戳
 * @returns {string} 相对时间字符串
 */
export function formatRelativeTime(timestamp) {
  if (!timestamp) return ''
  
  const ts = timestamp.toString().length === 10 ? timestamp * 1000 : timestamp
  const now = Date.now()
  const diff = now - ts
  
  const minute = 60 * 1000
  const hour = minute * 60
  const day = hour * 24
  const week = day * 7
  const month = day * 30
  const year = day * 365
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < week) {
    return `${Math.floor(diff / day)}天前`
  } else if (diff < month) {
    return `${Math.floor(diff / week)}周前`
  } else if (diff < year) {
    return `${Math.floor(diff / month)}月前`
  } else {
    return `${Math.floor(diff / year)}年前`
  }
}

/**
 * 获取星期几
 * @param {number} timestamp - 时间戳
 * @returns {string} 星期几
 */
export function getWeekDay(timestamp) {
  if (!timestamp) return ''
  
  const ts = timestamp.toString().length === 10 ? timestamp * 1000 : timestamp
  const date = new Date(ts)
  const weekDays = ['日', '一', '二', '三', '四', '五', '六']
  return `星期${weekDays[date.getDay()]}`
}

/**
 * 格式化时间为指定格式（类似 moment.js 的格式）
 * @param {number} timestamp - 时间戳
 * @param {string} formatStr - 格式字符串，如 'YYYY-MM-DD HH:mm:ss'
 * @returns {string} 格式化后的时间
 */
export function formatTime(timestamp, formatStr = 'YYYY-MM-DD HH:mm:ss') {
  if (!timestamp) return ''
  
  const ts = timestamp.toString().length === 10 ? timestamp * 1000 : timestamp
  const date = new Date(ts)
  
  const formatMap = {
    'YYYY': date.getFullYear(),
    'MM': String(date.getMonth() + 1).padStart(2, '0'),
    'DD': String(date.getDate()).padStart(2, '0'),
    'HH': String(date.getHours()).padStart(2, '0'),
    'mm': String(date.getMinutes()).padStart(2, '0'),
    'ss': String(date.getSeconds()).padStart(2, '0'),
    'M': date.getMonth() + 1,
    'D': date.getDate(),
    'H': date.getHours(),
    'm': date.getMinutes(),
    's': date.getSeconds()
  }
  
  return formatStr.replace(/YYYY|MM|DD|HH|mm|ss|M|D|H|m|s/g, match => formatMap[match])
}

/**
 * 获取当前时间戳
 * @param {boolean} isSeconds - 是否返回秒级时间戳，默认false返回毫秒
 * @returns {number} 时间戳
 */
export function getCurrentTimestamp(isSeconds = false) {
  const timestamp = Date.now()
  return isSeconds ? Math.floor(timestamp / 1000) : timestamp
}

export default {
  formatTimestamp,
  formatRelativeTime,
  getWeekDay,
  formatTime,
  getCurrentTimestamp
}